﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Tzx.Tools.Payroll2Images.Exe.Api;

namespace Tzx.Tools.Payroll2Images.Exe.FilesSender
{
    /// <summary>
    /// 将命名文件调用API发送
    /// </summary>
    public partial class UcSenderV2 : UserControl
    {

        #region 初始化

        /// <summary>
        /// 构造
        /// </summary>
        public UcSenderV2()
        {
            InitializeComponent();

            Load += UcSenderV2_Load; //加载时
            LvFiless.ItemChecked += LvFiless_ItemChecked; //列表勾选事件
        }

        /// <summary>
        /// 加载时
        /// </summary>
        private void UcSenderV2_Load(object sender, EventArgs e)
        {
            const string READ_TEXT = @"文件名中需包含接收人“中文名/英文名/工号”至少一项，如文件名“李大明Tom00365.jpg”";
            LblReadText.Text = READ_TEXT;

            Sender.InitListView(LvFiless);//初始设置列表控件
        }

        /// <summary>
        /// 标题
        /// </summary>
        private string Title
        {
            get
            {
                if (ParentForm == null)
                {
                    return String.Empty;
                }
                return ParentForm.Text;
            }
        }

        #endregion

        #region public

        /// <summary>
        /// 外部赋值
        /// </summary>
        /// <param name="directory"></param>
        public void SendDirectory(string directory)
        {
            TxtFilesInFolder.Text = string.Format("{0}", directory);
            Sender.FillFileSs(directory, LvFiless);//加载到列表
        }

        #endregion

        #region 事件方法_按钮(文件夹选择)

        /// <summary>
        /// 1.选择文件夹
        /// </summary>
        private void BtnSelect_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件夹路径";
            dialog.ShowNewFolderButton = true;

            //初始位置
            string dir = string.Format("{0}", TxtFilesInFolder.Text).Trim();
            if (dir != string.Empty)
            {
                if (Directory.Exists(dir))
                {
                    dialog.SelectedPath = dir; //选择文件夹的位置
                }
            }
            else
            {
                dialog.SelectedPath = Application.StartupPath; //EXE应用程序的位置
            }

            //加载
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.SelectedPath;
                TxtFilesInFolder.Text = path;
                Sender.FillFileSs(path, LvFiless);//加载到列表
            }
        }

        /// <summary>
        /// 2.重新加载到列表
        /// </summary>
        private void BtnFill_Click(object sender, EventArgs e)
        {
            string dir = TxtFilesInFolder.Text;
            if (!Directory.Exists(dir))
            {
                MessageBox.Show("文件夹不存在", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            Sender.FillFileSs(dir, LvFiless);//加载到列表
        }

        /// <summary>
        /// 3.打开文件夹
        /// </summary>
        private void BtnOpenFolder_Click(object sender, EventArgs e)
        {
            string dir = TxtFilesInFolder.Text;
            if (!Directory.Exists(dir))
            {
                MessageBox.Show("文件夹不存在", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            Process.Start(dir);
        }

        /// <summary>
        /// 4.移除所选
        /// </summary>
        private void LnkRemove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string text = "确定要将已勾选文件从任务列表中移除？\n\n(不是删除文件)";
            if (MessageBox.Show(text, "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            //从后面开始
            int count = LvFiless.Items.Count;
            for (int idx = count - 1; idx >= 0; idx--)
            {
                if (LvFiless.Items[idx].Checked)
                {
                    LvFiless.Items.RemoveAt(idx);
                }
            }//for
        }

        #endregion

        #region 事件方法_按钮(发送,获取状态)

        /// <summary>
        /// 0.全部勾选
        /// </summary>
        private void CbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            bool isChecked = CbCheckAll.Checked;
            foreach (ListViewItem lvi in LvFiless.Items)
            {
                lvi.Checked = isChecked;
            }
        }

        /// <summary>
        /// 1.提交发送
        /// </summary>
        private void BtnBeginSend_Click(object sender, EventArgs e)
        {
            int count_checked = Sender.GetCheckedItems(LvFiless).Count;
            if (count_checked == 0)
            {
                MessageBox.Show("没有勾选任何文件", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //
            string text = string.Format("开始将已勾选的{0}个文件提交发送？", count_checked);
            if (MessageBox.Show(text, "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            //开始
            panel4Bottom.Enabled = false;
            LvFiless.Enabled = false;
            Cursor = Cursors.WaitCursor;

            try
            {
                Sender.Do_Submit_Checked(LvFiless,progressBar1,lblProgress);//提交发送按钮
            }
            finally
            {
                //结束
                panel4Bottom.Enabled = true;
                LvFiless.Enabled = true;
                Cursor = Cursors.Default;

                progressBar1.Value = 0;//重置
            }
        }

        /// <summary>
        /// 2.刷新发送进度
        /// </summary>
        private void BtnRefreshProgress_Click(object sender, EventArgs e)
        {
            int count_checked = Sender.GetCheckedItems(LvFiless).Count;
            if (count_checked == 0)
            {
                MessageBox.Show("没有勾选任何文件", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //开始
            panel4Bottom.Enabled = false;
            LvFiless.Enabled = false;
            Cursor = Cursors.WaitCursor;

            try
            {
                Sender.Do_RenewSendStatus_Checked(false,LvFiless,progressBar1,lblProgress);//刷新发送进度按钮
            }
            finally
            {
                //结束
                panel4Bottom.Enabled = true;
                LvFiless.Enabled = true;
                Cursor = Cursors.Default;

                progressBar1.Value = 0;//重置
            }
        }

        /// <summary>
        /// 3.刷新结果状态(阅读状态)
        /// </summary>
        private void BtnRefreshStatus_Click(object sender, EventArgs e)
        {
            int count_checked = Sender.GetCheckedItems(LvFiless).Count;
            if (count_checked == 0)
            {
                MessageBox.Show("没有勾选任何文件", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //开始
            panel4Bottom.Enabled = false;
            LvFiless.Enabled = false;
            Cursor = Cursors.WaitCursor;

            try
            {
                Sender.Do_RenewReadStatus_Checked(LvFiless,progressBar1,lblProgress);//刷新结果阅读按钮
            }
            finally
            {
                //结束
                panel4Bottom.Enabled = true;
                LvFiless.Enabled = true;
                Cursor = Cursors.Default;

                progressBar1.Value = 0;//重置
            }
        }

        /// <summary>
        /// 4.撤回
        /// </summary>
        private void BtnRecall_Click(object sender, EventArgs e)
        {
            int count_checked = Sender.GetCheckedItems(LvFiless).Count;
            if (count_checked == 0)
            {
                MessageBox.Show("没有勾选任何文件", Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            //
            string text = string.Format("确定要将已勾选的{0}个已提交发送成功的消息撤回？\n\n(仅能撤回24小时以内的消息)", count_checked);
            if (MessageBox.Show(text, "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            //开始
            panel4Bottom.Enabled = false;
            LvFiless.Enabled = false;
            Cursor = Cursors.WaitCursor;
            
            try
            {
                Sender.Do_Recall_Checked(LvFiless,progressBar1,lblProgress);//撤回按钮
            }
            finally
            {
                //结束
                panel4Bottom.Enabled = true;
                LvFiless.Enabled = true;
                Cursor = Cursors.Default;

                progressBar1.Value = 0;//重置
            }
        }

        #endregion

        #region 事件方法_右键菜单和列表勾选

        /// <summary>
        /// 1.复制全部
        /// </summary>
        private void MnuCopyAll_Click(object sender, EventArgs e)
        {
            string fullText = Sender.GetListViewText(LvFiless);
            if (string.IsNullOrEmpty(fullText)) return;

            //复制到剪切板
            Clipboard.SetText(fullText);
            MessageBox.Show("标题及全部行已复制到剪切板", Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 2.复制选中行
        /// </summary>
        private void MnuCopyRow_Click(object sender, EventArgs e)
        {
            List<int> rowIndex;
            string fullText = Sender.GetListViewRowText(LvFiless, out rowIndex);
            if (string.IsNullOrEmpty(fullText)) return;

            //复制到剪切板
            Clipboard.SetText(fullText);
            MessageBox.Show(
                string.Format("选中{0}行已复制到剪切板",rowIndex.Count == 1 ? "第" + (rowIndex[0] + 1) + "" : "共有" + rowIndex.Count + ""),
                Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 3.按钮,暂存临时文件
        /// </summary>
        private void MnuSaveList_Click(object sender, EventArgs e)
        {
            string message;
            bool ok = Sender.SaveTempFile(LvFiless,out message);
            if (ok)
            {
                MessageBox.Show("已暂存到临时文件【" + Sender.TEMP_FILE_NAME_SENDER + "】", Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 4.按钮,从临时文件中加载
        /// </summary>
        private void MnuLoadList_Click(object sender, EventArgs e)
        {
            //将清空已有列表
            if (LvFiless.Items.Count > 0)
            {
                if (DialogResult.Yes !=
                    MessageBox.Show("将清空现有列表清单，是否继续？", Title, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    )
                {
                    return;
                }
            }

            //
            string message;
            bool ok = Sender.LoadTemplate(LvFiless,out message);
            if (!ok)
            {
                MessageBox.Show(message, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        /// <summary>
        /// 5.按钮,删除临时文件
        /// </summary>
        private void MnuDeleteTempFile_Click(object sender, EventArgs e)
        {
            string json_file = Path.Combine(Application.StartupPath, Sender.TEMP_FILE_NAME_SENDER);
            if (File.Exists(json_file))
            {
                File.Delete(json_file);
                MessageBox.Show("临时文件【" + Sender.TEMP_FILE_NAME_SENDER + "】已删除", Title, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }
        }

        /// <summary>
        /// 列表项用户勾选时
        /// </summary>
        private void LvFiless_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            bool isChecked = e.Item.Checked;
            ApiStatus status = e.Item.Tag as ApiStatus;
            if (status != null)
            {
                status.is_checked = isChecked;
            }
        }

        #endregion

    }
}
